<template>
	<view class="container">
		<!-- 餐厅头部 -->
		<view class="restaurant-header">
			<view class="header-content">
				<text class="name">{{ restaurant.name }}</text>
				<view class="meta-info">
					<view class="rating">
						<uni-icons type="star-filled" size="16" color="#FFD700"></uni-icons>
						<text>{{ restaurant.rating }}</text>
					</view>
					<view class="location">
						<uni-icons type="location-filled" size="16" color="#FF6B6B"></uni-icons>
						<text>{{ restaurant.location }}</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 主体内容 -->
		<view class="main-content">
			<!-- 分类导航 -->
			<scroll-view class="category-nav" scroll-y>
				<view v-for="(category, index) in categories" :key="index" class="nav-item"
					:class="{ 'active': selectedCategory === index }" @click="onCategorySelect(index)">
					<text class="nav-text">{{ category }}</text>
				</view>
			</scroll-view>

			<!-- 餐品列表 -->
			<scroll-view class="food-list" scroll-y>
				<!-- 加载状态 -->
				<view v-if="isLoading" class="loading-state">
					<uni-icons type="spinner-cycle" size="28" color="#FF6B6B" class="loading-icon"></uni-icons>
					<text class="loading-text">加载餐品中...</text>
				</view>

				<!-- 空状态 -->
				<view v-else-if="filteredFoods.length === 0" class="empty-state">
					<image src="/static/empty-food.png" class="empty-image"></image>
					<text class="empty-text">当前分类暂无餐品</text>
				</view>

				<!-- 餐品卡片 -->
				<view v-for="(food, index) in filteredFoods" :key="index" class="food-card"
					:class="{ 'sold-out': food.state === 0 }"
					@click="food.state === 1 && handleFoodDetail(food.itemId)">
					<!-- 添加售罄遮罩 -->
					<view v-if="food.state === 0" class="sold-out-mask">
						<text class="sold-out-text">已售罄</text>
					</view>

					<image class="food-image" :src="food.imageUrl" mode="aspectFill"
						:style="{ filter: food.state === 0 ? 'grayscale(100%)' : 'none' }" />

					<view class="food-info">
						<view class="info-header">
							<text class="food-name" :style="{ color: food.state === 0 ? '#999' : '#333' }">
								{{ food.name }}
							</text>
							<text class="food-price" :style="{ color: food.state === 0 ? '#999' : '#FF6B6B' }">
								¥{{ food.price }}
							</text>
						</view>
						<!-- <text class="food-sales">已售 {{ food.sales }} 份</text> -->
						<view class="rating">
							<uni-icons type="star-filled" size="16" color="#FFD700"></uni-icons>
							<text>{{ food.rating }}</text>
						</view>
						<view class="cart-control">
							<view v-if="getCartItem(food.itemId)" class="quantity-control">
								<view class="btn minus" @click.stop="decreaseQuantity(getCartItem(food.itemId))">-
								</view>
								<text class="quantity">{{ getCartItem(food.itemId).quantity }}</text>
								<view class="btn plus" @click.stop="increaseQuantity(getCartItem(food.itemId))">+</view>
							</view>
							<view v-else class="add-btn" @click.stop="addToCart(food)"
								:class="{ disabled: food.state === 0 }">
								<text>{{ food.state === 1 ? '加入购物车' : '已售罄' }}</text>
							</view>
						</view>
					</view>
				</view>

			</scroll-view>
		</view>

		<!-- 底部购物车栏 -->
		<view class="cart-bar">
			<view class="cart-icon" @click="openCartPopup">
				<uni-icons type="cart" size="28" color="#fff"></uni-icons>
				<view v-if="cart.length > 0" class="badge">{{ cartTotalQuantity }}</view>
			</view>
			<view class="price-info">
				<text class="total-price">¥{{ totalPrice }}</text>
				<text class="hint-text">({{ cartTotalQuantity }}件商品)</text>
			</view>
			<view class="checkout-btn" @click="goToOrder">去结算</view>
		</view>

		<!-- 购物车弹窗 -->
		<uni-popup ref="cartPopupRef" type="bottom">
			<view class="cart-popup">
				<view class="popup-header">
					<text class="title">购物车 ({{ cartTotalQuantity }})</text>
					<uni-icons type="close" size="20" @click="cartPopupRef.close()"></uni-icons>
				</view>

				<scroll-view class="cart-list" scroll-y>
					<view v-if="cart.length === 0" class="empty-cart">
						<image src="/static/empty-cart.png" class="empty-image"></image>
						<text class="empty-text">购物车空空如也</text>
					</view>

					<view v-for="(item, index) in cart" :key="index" class="cart-item">
						<view class="item-info">
							<text class="name">{{ item.name }}</text>
							<text class="price">¥{{ item.price }}</text>
						</view>
						<view class="quantity-control">
							<view class="btn minus" @click="decreaseQuantity(item)">-</view>
							<text class="quantity">{{ item.quantity }}</text>
							<view class="btn plus" @click="increaseQuantity(item)">+</view>
						</view>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<text class="total">合计: ¥{{ totalPrice }}</text>
					<view class="checkout-btn" @click="goToOrder">立即结算</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		toRaw,
		onMounted // 引入 onMounted
	} from 'vue';
	import {
		navigateTo
	} from '@dcloudio/uni-app';
	import {
		useCartStore
	} from '../../stores/cart';
	import {
		getResDetail
	} from '../../request/api';

	// 路由对象
	const resuid = ref('');

	// 模拟餐厅信息
	const restaurant = ref({});

	// 餐品类型列表
	const categories = ref([]);
	// 选中的餐品类型索引
	const selectedCategory = ref(0);

	// 模拟餐品数据，添加了图片链接和销量字段
	const foods = ref([]);

	// 购物车
	const cart = ref([]);

	// 控制购物车弹出层显示隐藏
	const cartPopupRef = ref(null);

	// 计算过滤后的餐品列表
	const filteredFoods = computed(() => {
		return foods.value.filter(
			(food) => food.category === categories.value[selectedCategory.value]
		);
	});

	// 计算购物车总价
	const totalPrice = computed(() => {
		return cart.value.reduce((total, item) => {
			return total + item.price * item.quantity;
		}, 0);
	});

	// 修改购物车相关计算属性
	const cartTotalQuantity = computed(() => {
		return cart.value.reduce((total, item) => total + item.quantity, 0);
	});

	// 处理餐品类型选择事件
	const onCategorySelect = (index) => {
		selectedCategory.value = index;
	};

	// 加入购物车方法
	const addToCart = (food) => {
		if (food.state !== 1) return;

		const existingIndex = cart.value.findIndex(item => item.itemId === food.itemId);
		if (existingIndex > -1) {
			cart.value[existingIndex].quantity++;
		} else {
			// 使用响应式方式添加
			cart.value = [...cart.value, {
				...food,
				quantity: 1
			}];
		}
	};

	// 减少商品数量
	const decreaseQuantity = (item) => {
		if (item.quantity > 1) {
			item.quantity--;
		} else {
			const index = cart.value.findIndex(cartItem => cartItem.itemId === item.itemId);
			if (index !== -1) {
				cart.value.splice(index, 1);
			}
		}
	};

	// 增加商品数量
	const increaseQuantity = (item) => {
		item.quantity++;
	};

	// 从购物车移除商品
	const removeFromCart = (item) => {
		const index = cart.value.findIndex(cartItem => cartItem.itemId === item.itemId);
		if (index !== -1) {
			cart.value.splice(index, 1);
		}
	};

	// 前往下单方法
	const goToOrder = () => {
		const realCartData = toRaw(cart.value);
		if (realCartData.length) {
			const cartStore = useCartStore();
			cartStore.setCart(realCartData);
			cartStore.setResturant(restaurant.value);
			handleJump('/subpackage/submitOrder/index');
		} else uni.showToast({
			title: `请选择餐品`,
			icon: 'error'
		})

	};

	// 打开弹出层
	const openCartPopup = () => {
		cartPopupRef.value.open();
	};

	// 获取餐品在购物车中的数量
	const getCartQuantity = (itemId) => {
		const item = cart.value.find(item => item.itemId === itemId);
		return item ? item.quantity : 0;
	};

	// 获取购物车中的对应餐品对象
	const getCartItem = (itemId) => {
		return cart.value.find(item => item.itemId === itemId);
	};

	// 跳转页面函数
	const handleJump = (jumpSrc) => {
		uni.navigateTo({
			//保留当前页面，跳转到应用内的某个页面
			url: jumpSrc
		});
	};

	const handleFoodDetail = (itemId) => {
		handleJump(`/subpackage/foodDetail/index?id=${itemId}`)
	}

	const init = async () => {
		const res = await getResDetail(resuid.value);
		const resdetail = res.responseData
		if (resdetail) {
			// 更新餐厅信息
			restaurant.value = {
				id: resdetail.restaurant.restaurant_id,
				name: resdetail.restaurant.restaurant_name,
				rating: resdetail.restaurant.rating,
				location: resdetail.restaurant.location
			};
			// 更新餐品数据
			foods.value = resdetail.menuItems;
			// 更新餐品类型列表
			const newCategories = [];
			resdetail.menuItems.forEach(food => {
				if (!newCategories.includes(food.category)) {
					newCategories.push(food.category);
				}
			});
			categories.value = newCategories;
		}
	};

	// 使用 onMounted 确保在页面加载时执行
	onMounted(() => {
		const pages = getCurrentPages();
		const currentPage = pages[pages.length - 1];
		const options = currentPage.options;
		if (options.uid) {
			resuid.value = options.uid;
		}
		init();
	});
</script>

<style scoped>
	/* 颜色变量 */
	:root {
		--primary: #FF6B6B;
		--secondary: #6B8EFF;
		--text-primary: #333;
		--text-secondary: #666;
		--border-color: #eee;
		--bg-color: #f8f9fa;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background: var(--bg-color);
	}

	/* 餐厅头部 */
	.restaurant-header {
		background: #fff;
		padding: 16px 20px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
	}

	.header-content .name {
		font-size: 24px;
		font-weight: 600;
		color: var(--text-primary);
		margin-bottom: 8px;
	}

	.meta-info {
		display: flex;
		gap: 16px;
	}

	.rating,
	.location {
		display: flex;
		align-items: center;
		font-size: 14px;
		color: var(--text-secondary);
	}

	/* 主体内容 */
	.main-content {
		flex: 1;
		display: flex;
		margin-top: 8px;
		overflow: hidden;
	}

	/* 分类导航 */
	.category-nav {
		width: 120px;
		background: #fff;
		border-right: 1px solid var(--border-color);
	}

	.nav-item {
		padding: 18px 12px;
		border-left: 4px solid transparent;
		transition: all 0.2s;
	}

	.nav-item.active {
		border-left-color: var(--primary);
		background: #fff8f8;
	}

	.nav-text {
		font-size: 14px;
		color: var(--text-secondary);
	}

	.nav-item.active .nav-text {
		color: var(--primary);
		font-weight: 500;
	}

	/* 餐品列表 */
	.food-card.sold-out {
		position: relative;
		opacity: 0.7;
	}

	.sold-out-mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.9);
		z-index: 2;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.sold-out-text {
		transform: rotate(-15deg);
		font-size: 32px;
		font-weight: bold;
		color: #c0c4cc;
		letter-spacing: 4px;
		text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
	}

	.disabled {
		background: #c0c4cc !important;
		cursor: not-allowed;
	}

	.food-list {
		flex: 1;
		padding: 12px 16px 70px 16px;
	}

	.food-card {
		background: #fff;
		border-radius: 12px;
		margin-bottom: 16px;
		overflow: hidden;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
		position: relative;
		transition: all 0.3s ease;
	}

	.food-image {
		width: 100%;
		height: 180px;
	}

	.food-info {
		padding: 16px;
	}

	.info-header {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8px;
	}

	.food-name {
		font-size: 16px;
		font-weight: 500;
		color: var(--text-primary);
	}

	.food-price {
		font-size: 16px;
		color: var(--primary);
		font-weight: 600;
	}

	.food-sales {
		font-size: 12px;
		color: var(--text-secondary);
		margin-bottom: 12px;
	}

	.food-card.sold-out {
		pointer-events: none;
		/* 禁用点击事件 */
	}

	.food-card.sold-out .cart-control {
		pointer-events: auto;
		/* 允许购物车区域响应事件 */
	}

	.food-card.sold-out .food-name,
	.food-card.sold-out .food-price {
		text-decoration: line-through;
	}

	/* 购物车控制 */
	.cart-control {
		display: flex;
		justify-content: flex-end;
	}

	.add-btn {
		background: var(--primary);
		color: #fff;
		padding: 8px 16px;
		border-radius: 20px;
		font-size: 14px;
		transition: transform 0.1s;
	}

	.add-btn:active {
		transform: scale(0.95);
	}

	.quantity-control {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.btn {
		width: 28px;
		height: 28px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 500;
		transition: all 0.2s;
	}

	.btn.minus {
		background: #ffecec;
		color: var(--primary);
	}

	.btn.plus {
		background: #ffeded;
		color: var(--primary);
	}

	.quantity {
		min-width: 24px;
		text-align: center;
	}

	/* 底部购物车栏 */
	.cart-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 60px;
		background: #fff;
		display: flex;
		align-items: center;
		padding: 0 20px;
		box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
	}

	.cart-icon {
		width: 40px;
		height: 40px;
		background: var(--primary);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.badge {
		position: absolute;
		top: -4px;
		right: -4px;
		background: #ff4444;
		color: #fff;
		min-width: 18px;
		height: 18px;
		border-radius: 9px;
		font-size: 12px;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 4px;
	}

	.price-info {
		flex: 1;
		margin: 0 16px;
	}

	.total-price {
		font-size: 18px;
		color: var(--primary);
		font-weight: 600;
	}

	.hint-text {
		font-size: 12px;
		color: var(--text-secondary);
		margin-left: 8px;
	}

	.checkout-btn {
		background: var(--primary);
		color: #fff;
		padding: 12px 24px;
		border-radius: 20px;
		font-weight: 500;
	}

	/* 购物车弹窗 */
	.cart-popup {
		background: #fff;
		border-radius: 16px 16px 0 0;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		border-bottom: 1px solid var(--border-color);
	}

	.popup-header .title {
		font-size: 18px;
		font-weight: 500;
	}

	.cart-list {
		flex: 1;
		padding: 16px;
		width: 90%;
	}

	.cart-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 12px 0;
		border-bottom: 1px solid var(--border-color);
	}

	.popup-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16px;
		background: #f8f9fa;
	}

	/* 加载状态 */
	.loading-state {
		padding: 40px 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.loading-icon {
		animation: rotate 1s linear infinite;
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	/* 空状态 */
	.empty-state {
		padding: 40px 0;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.empty-image {
		width: 120px;
		height: 120px;
		opacity: 0.6;
		margin-bottom: 16px;
	}
	
	/* 添加购物车按钮过渡效果 */
	.cart-control {
	  transition: all 0.3s ease;
	}
	
	.quantity-control {
	  display: flex;
	  align-items: center;
	  gap: 10rpx;
	  background: #f5f5f5;
	  border-radius: 20rpx;
	  padding: 4rpx 12rpx;
	}
	
	.btn {
	  width: 40rpx;
	  height: 40rpx;
	  border-radius: 50%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  font-weight: bold;
	  background: #fff;
	  box-shadow: 0 2rpx 6rpx rgba(0,0,0,0.1);
	}
	
	.btn:active {
	  transform: scale(0.9);
	}
</style>